"""
    字符串操作
"""
import numpy as np
from pandas import Series, DataFrame
import pandas as pd
import re


def test_01():
    """
    字符串对象方法
    :return:
    """
    var = 'a,b,  guido'
    # print(var.split(','))
    # pieces = [x.strip() for x in var.split(',')]
    # print(pieces)
    # first, second, third = pieces
    # print(first+'::'+second+'::'+third)
    # print('::'.join(pieces))

    print('guido' in var)
    print(var.index(','))
    print(var.find(':'))
    print(var.count(','))
    print(var.replace(',', ':'))


def test_02():
    """
    正则表达式
    :return:
    """
    # text = "foo bar\t baz \tqux"
    # print(re.split('\s+', text))
    # regex = re.compile('\s+')
    # print(regex.split(text))
    # print(regex.findall(text))

    text = """Dave dave@google.com 
    Steve steve@google.com 
    Rob rob@google.com 
    Ryan ryan@yahoo.com
    """
    # pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
    # # re.IGNORECASE的作用是使正则表达式对大小写不敏感
    # regex = re.compile(pattern, flags=re.IGNORECASE)
    # print(regex.findall(text))
    # m = regex.search(text)
    # print(m)
    # print(text[m.start():m.end()])
    # print(regex.match(text))
    # print(regex.sub('REDACTED', text))

    pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
    # # re.IGNORECASE的作用是使正则表达式对大小写不敏感
    # regex = re.compile(pattern, flags=re.IGNORECASE)
    # m = regex.match('wesm@bright.net')
    # # print(m.groups())
    # # print(regex.findall(text))
    # print(regex.sub(r'Username: \1. Domain: \2, Suffix: \3', text))

    regex = re.compile(r"""
        (?P<username>[A-Z0-9._%+-]+)
        @
        (?P<domain>[A-Z0-9.-]+)
        \.
        (?P<suffix>[A-Z]{2,4})""", flags=re.IGNORECASE | re.VERBOSE)
    m = regex.match('wesm@bright.net')
    print(m)
    print(m.groupdict())


def test_03():
    """
    pandas中矢量化的字符串函数
    :return:
    """
    data = {'Dave': 'dave@google.com', 'Steve': 'steve@gmail.com', 'Rob': 'rob@gmail.com', 'Wes': np.nan}
    data = Series(data)
    # print(data)
    # print(data.isnull())
    # print(data.str.contains('gmail'))

    pattern = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'
    # print(pattern)
    # print(data.str.findall(pattern, flags=re.IGNORECASE))

    # ?结果和书上不一致
    matches = data.str.match(pattern, flags=re.IGNORECASE)
    # print(matches)
    # print(matches.str.get(1))
    # print(matches.str[0])

    print(data.str[:5])


def main():
    # test_01()
    # test_02()
    test_03()


if __name__ == '__main__':
    main()
